using System;
using System.Reflection;
using System.Collections.Generic;
using System.Text;

namespace Crainiate.Data.Persistence.Providers
{
    public static class Common
    {
        //Get the storage name for the type formatted without the prefix
        public static string GetTypeName(Type type, string prefix)
        {
            string fullname = type.FullName;

            if (prefix == null || prefix == string.Empty || !fullname.StartsWith(prefix)) return fullname;
            fullname = fullname.Replace(prefix, "");
            if (fullname.StartsWith(".")) fullname = fullname.Substring(1);

            return fullname;
        }

        //Get the name of a query
        public static string GetQueryName(IQuery query)
        {
            return query.GetHashCode().ToString().Replace("-", "0");
        }

        public static Type GetPersistType(IPersistable graph)
        {
            if (graph is IView)
            {
                IView view = (IView) graph;
                return view.UnderlyingType();
            }

            return graph.GetType();
        }

        public static Type GetPersistType(Type type)
        {
            if (!typeof(IView).IsAssignableFrom(type)) return type;

            //Get the view type
            while (!type.IsGenericType)
            {
                type = type.BaseType;
            }

            //Get the type used in the generic
            return type.GetGenericArguments()[0];
        }

        public static PropertyInfo[] GetCommonProperties(PropertyInfo[] a, PropertyInfo[] b)
        {
            List<PropertyInfo> list = new List<PropertyInfo>();

            foreach (PropertyInfo prop in a)
            {
                foreach (PropertyInfo prop2 in b)
                {
                    if (prop.Name == prop2.Name)
                    {
                        list.Add(prop);
                        break;
                    }
                }
            }

            return list.ToArray();
        }
    }
}
